//
//  UIColor+Extension.swift
//  ESMusic
//
//  Created by Hood on 2022/7/31.
//

import Foundation
import UIKit

extension UIColor {
    public static var randomColor: UIColor {
        return UIColor(red: CGFloat(arc4random() % 256) / 255.0, green: CGFloat(arc4random() % 256) / 255.0, blue: CGFloat(arc4random() % 256) / 255.0, alpha: 1.0)
    }

    // MARK: - 根据十六进制获取颜色

    public class func hexColor(_ hex: String) -> UIColor {
        ///  支持格式包括： #ff21af64   #21af64   0x21af64
        if hex.hasPrefix("#") || (hex.hasPrefix("0x")) {
            let mutStr = (hex as NSString).mutableCopy() as! NSMutableString

            if hex.hasPrefix("#") {
                mutStr.deleteCharacters(in: NSRange(location: 0, length: 1))
            } else {
                mutStr.deleteCharacters(in: NSRange(location: 0, length: 2))
            }

            if mutStr.length == 6 {
                mutStr.insert("ff", at: 0)
            }

            let aStr = mutStr.substring(with: NSRange(location: 0, length: 2))
            let rStr = mutStr.substring(with: NSRange(location: 2, length: 2))
            let gStr = mutStr.substring(with: NSRange(location: 4, length: 2))
            let bStr = mutStr.substring(with: NSRange(location: 6, length: 2))

            let alpha = aStr.hexValue()
            let red = rStr.hexValue()
            let green = gStr.hexValue()
            let blue = bStr.hexValue()

            return UIColor(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha) / 255.0)
        } else {
            assert(false, "16进制字符串转UIColor：格式不支持")
            return .clear
        }
    }
}
